{extend name="common/base"/}
{block name="style"}
<style>
    .upload-img {
        width: 120px;
        height: 90px;
        overflow: hidden;
        position: relative;
        border: 1px solid #eee;
        padding: 1px;
        margin: 5px;
        float: left;
    }

    .upload-close {
        position: absolute;
        top: 1px;
        right: 1px;
    }
    /* 新增样式 */
    .input-group, .display-group {
        margin-bottom: 10px;
    }
    .input-group label, .display-group label {
        display: inline-block;
        width: 120px;
        text-align: right;
        margin-right: 10px;
    }
    .input-group input, .display-group input, .input-group select {
        width: 200px;
        padding: 5px;
    }
    /* 规格值选项卡样式 - 带分割线 */
    .spec-value-options {
        display: inline-flex;
        align-items: center;
        flex-wrap: wrap;
        gap: 15px;
        padding: 5px 0;
    }
    .spec-value-item {
        display: inline-flex;
        align-items: center;
        position: relative;
    }
    /* 分割线样式 */
    .spec-value-item:not(:first-child)::before {
        content: "";
        position: absolute;
        left: -10px;
        width: 1px;
        height: 16px;
        background-color: #ddd;
    }
    .spec-value-options input[type="radio"] {
        margin-right: 5px;
    }
    .m-col-sm-2{ width: 33%; float: left; margin: 0 0 10px;}
    #initial-prices {
        width: 100%;
        height: 120px;
        padding: 8px;
        border: 1px solid #e6e6e6;
        border-radius: 4px;
        resize: vertical; /* 允许垂直拉伸 */
    }
    .text-danger {
        color: #FF5722;
        font-size: 12px;
    }
    .mt-1 { margin-top: 5px; }
    .mt-2 { margin-top: 10px; }
    /* 多选框容器样式 */
    .spec-value-checkboxes {
        display: inline-block;
        vertical-align: middle;
    }
    .spec-value-checkboxes label {
        display: inline-block ! important;
        margin-bottom: 8px !important;
        text-align: left !important;
        width: auto;
    }
    .spec-value-checkboxes input[type="checkbox"] {
        margin-right: 5px;
        width: 18px;
        height: 18px;
        float: left;
    }
    .pl-box{ text-align: center;}
    .pl-box .input-group{ text-align: left;}
    .pl-box .layui-input { display: inline-block;}
    .pl-box .text-danger{ text-align: center;}
    #confirmBatchUpdate{ margin: 0 auto;}

    /* 标签删除与编辑功能样式 */
    .tag-container {
        display: flex;
        flex-wrap: wrap;
        gap: 8px;
        padding: 5px;
        border: 1px solid #e6e6e6;
        border-radius: 4px;
        min-height: 38px; /* 与输入框高度一致 */
    }
    .tag-item {
        display: inline-flex;
        align-items: center;
        padding: 2px 8px;
        background-color: #f2f2f2;
        border-radius: 4px;
        font-size: 14px;
        position: relative;
        cursor: text; /* 提示可编辑 */
    }
    .tag-close {
        margin-left: 5px;
        cursor: pointer;
        color: #666;
        font-size: 16px;
        line-height: 1;
    }
    .tag-close:hover {
        color: #ff4d4f;
    }
    .hidden-input {
        display: none; /* 隐藏原始输入框，用标签容器替代显示 */
    }
    /* 编辑状态样式 */
    .tag-item.editing {
        background-color: #fff;
        border: 1px dashed #666;
        padding: 0;
    }
    .tag-input {
        border: none;
        outline: none;
        background: transparent;
        font-size: 14px;
        padding: 2px 8px;
        width: 100px; /* 编辑框宽度 */
    }
</style>
{/block}
<!-- 主体 -->
{block name="body"}
<form class="layui-form p-page">
    <h3 class="pb-3">编辑商品</h3>
    <table class="layui-table layui-table-form">
        <tr>
            <td class="layui-td-gray">SPU</td>
            <td>{$detail.spu_id}</td>
            <td class="layui-td-gray">sku</td>
            <td>{$detail.sku_id}</td>
            <td class="layui-td-gray">店铺名称</td>
            <td>{$address_name}</td>
        </tr>
        <tr>
            <td class="layui-td-gray">标题</td>
            <td colspan="5">
                <input type="text" name="title" lay-verify="required|title"  lay-reqText="请输入标题" placeholder="请填写标题" class="layui-input" value="{$detail.title}" ></td>
        </tr>
        <tr>
            <td class="layui-td-gray">来源URL</td>
            <td colspan="5">
                <input type="text" id="banner" name="banner" lay-reqText="请输入来源URL" placeholder="请填写来源URL" class="layui-input" value="{$detail.banner}" lay-verify="url">
            </td>
        </tr>
        <tr>
            <td class="layui-td-gray" style="width:75px;">供应商名称</td>
            <td>
                <input type="text" name="desc"  lay-reqText="请输入供应商名称" placeholder="请输入供应商名称"  value="{$detail.desc}" class="layui-input">
            </td>
        </tr>
        <tr>
            <td class="layui-td-gray">基础价格</td>
            <td>
                <input type="text" name="base_price" lay-verify="required|number" lay-reqText="请输入基础价格" placeholder="请输入基础价格"
                       class="layui-input" value="{$detail.base_price}">
            </td>
        </tr>
        <tr>
            <td class="layui-td-gray">规格1名称</td>
            <td>
                <input type="text" name="sku_key"  lay-reqText="请输入规格1名称" placeholder="请输入规格1名称" class="layui-input" value="{$detail.sku_key}">
            </td>
        </tr>
        <tr>
            <td class="layui-td-gray">规格1值</td>
            <td colspan="5">
                <!-- 标签容器（可视化展示） -->
                <div class="tag-container" id="skuValue1Container"></div>
                <!-- 隐藏的原始输入框（用于表单提交） -->
                <input type="text" name="sku_value"
                       lay-reqText="请输入规格1值"
                       placeholder="请输入规格1值（多个值用|分隔）"
                       class="layui-input hidden-input"
                       value="{$detail.sku_value}"
                       id="skuValue1">
                <p class="layui-text text-danger mt-1">提示：点击文本编辑，点击×删除（会联动删除表格关联数据）</p>
            </td>
        </tr>
        <tr>
            <td class="layui-td-gray">规格2名称</td>
            <td>
                <input type="text" name="sku_key2"  lay-reqText="请输入规格2名称" placeholder="请输入规格2名称" class="layui-input" value="{$detail.sku_key2}">
            </td>
        </tr>
        <tr>
            <td class="layui-td-gray">规格2值</td>
            <td colspan="5">
                <!-- 标签容器（可视化展示） -->
                <div class="tag-container" id="skuValue2Container"></div>
                <!-- 隐藏的原始输入框（用于表单提交） -->
                <input type="text" name="sku_value2"
                       lay-reqText="请输入规格2值"
                       placeholder="请输入规格2值（多个值用|分隔）"
                       class="layui-input hidden-input"
                       value="{$detail.sku_value2}"
                       id="skuValue2">
                <p class="layui-text text-danger mt-1">提示：点击文本编辑，点击×删除（会联动删除表格关联数据）</p>
            </td>
        </tr>
        <tr>
            <td class="layui-td-gray">规格3名称</td>
            <td>
                <input type="text" name="sku_key3"  lay-reqText="请输入规格3名称" placeholder="请输入规格3名称" class="layui-input" value="{$detail.sku_key3}">
            </td>
            <td class="layui-td-gray">规格3值</td>
            <td>
                <!-- 标签容器（可视化展示） -->
                <div class="tag-container" id="skuValue3Container"></div>
                <!-- 隐藏的原始输入框（用于表单提交） -->
                <input type="text" name="sku_value3"
                       lay-reqText="请输入规格3值"
                       placeholder="请输入规格3值（多个值用|分隔）"
                       class="layui-input hidden-input"
                       value="{$detail.sku_value3}"
                       id="skuValue3">
                <p class="layui-text text-danger mt-1">提示：点击文本编辑，点击×删除（会联动删除表格关联数据）</p>
            </td>
        </tr>
        <tr>
            <td class="layui-td-gray">佣金选择</td>
            <td>
                <select name="commission" lay-verify="required" lay-reqText="请选择佣金">
                    {volist name="nav" id="v"}
                    <option value="{$v.id}" {eq name="$detail.commission" value="$v.id"}selected{/eq} yongjin="{$v.desc.0}" ad="{$v.desc.1}" dianpu="{$v.desc.2}" >{$v.title}</option>
                    {/volist}
                </select>
            </td>
        </tr>
        <tr>
            <td class="layui-td-gray">采购价格(¥)</td>
            <td>
                <input type="text" name="caigou" value="{$detail.caigou}" lay-reqText="请输入采购价格" placeholder="请输入采购价格" class="layui-input" lay-verify="number"  oninput="convertToYen(this, 'm_yuan')">
                <span class="layui-text">日元：<span riyuan="{notempty name="$config.riyuan" }{$config.riyuan}{/notempty}" id="m_yuan"></span></span>
            </td>
            <td class="layui-td-gray">物流运费(¥)</td>
            <td>
                <input type="text" name="wuliu" value="{$detail.wuliu}" lay-reqText="请输入物流运费" placeholder="请输入物流运费" class="layui-input" lay-verify="number" oninput="convertToYen(this, 'm_wuliu')">
                <span class="layui-text">日元：<span riyuan="{notempty name="$config.riyuan" }{$config.riyuan}{/notempty}" id="m_wuliu"></span></span>
            </td>
        </tr>
        <tr>
            <td class="layui-td-gray">佣金计算器</td>
            <td colspan="5">
                <div class="input-group">
                    <label for="selling-price">售价 (日元)</label>
                    <input type="number" id="selling-price" placeholder="输入售价" oninput="calculateProfit()">
                </div>
                <div class="display-group">
                    <div class="m-col-sm-2">
                        <label for="platform-commission">平台佣金 (日元)</label>
                        <input type="number" id="platform-commission" readonly>
                    </div>
                    <div class="m-col-sm-2">
                        <label for="ad-cost">广告 (日元)</label>
                        <input type="number" id="ad-cost" readonly>
                    </div>
                    <div class="m-col-sm-2">
                        <label for="owner-commission">店主抽佣 (日元)</label>
                        <input type="number" id="owner-commission" readonly>
                    </div>
                    <div class="m-col-sm-2">
                        <label for="payout">回款 (日元)</label>
                        <input type="number" id="payout" readonly>
                    </div>
                    <div class="m-col-sm-2">
                        <label for="profit">利润 (日元)</label>
                        <input type="number" id="profit" readonly>
                    </div>
                    <div class="m-col-sm-2">
                        <label for="profit-margin">利润率 (%)</label>
                        <input type="text" id="profit-margin" readonly>
                    </div>
                </div>
            </td>
        </tr>
        <tr>
            <td class="layui-td-gray">批量修改</td>
            <td colspan="5">
                <button type="button" class="layui-btn layui-btn-normal" id="showSpecModal">价格库存修改</button>
            </td>
        </tr>
    </table>
    <table class="layui-hide" id="link" lay-filter="link"></table>
    <div class="pt-3" style="margin-top: 30px;">
        <input type="hidden" name="id" value="{$detail.id}">
        <button class="layui-btn layui-btn-normal" lay-submit="" lay-filter="webform">立即提交</button>
        <button type="reset" class="layui-btn layui-btn-primary">重置</button>
        <button lay-event="back" class="layui-btn layui-btn-primary">关闭</button>
    </div>
</form>
<script type="text/html" id="listRemove">
    <div class="layui-btn-group listRemove">
        <a  class="layui-btn layui-btn-danger" style="margin-left: 10px !important;;" lay-event="del">删除</a>
    </div>
</script>
{/block}
<!-- /主体 -->


<!-- 脚本 -->
{block name="script"}
<script>
    Array.prototype.indexOf = function (val) {
        for (var i = 0; i < this.length; i++) {
            if (this[i] == val) return i;
        }
        return -1;
    };
    Array.prototype.remove = function (val) {
        var index = this.indexOf(val);
        if (index > -1) this.splice(index, 1);
    };

    // 存储规格值与表格行ID的映射关系
    const specValueRowMap = {
        sku1: {},
        sku2: {},
        sku3: {}
    };

    // 价格计算函数
    function calculateProfit() {
        const sellingPrice = Number(document.getElementById('selling-price').value) || 0;
        const caigou = document.getElementById('m_yuan').textContent ? Number(document.getElementById('m_yuan').textContent) : 0;
        const wuliu = document.getElementById('m_wuliu').textContent ? Number(document.getElementById('m_wuliu').textContent) : 0;

        const commissionSelect = document.querySelector('select[name="commission"]');
        const selectedOption = commissionSelect.options[commissionSelect.selectedIndex];
        const platformRate = (Number(selectedOption.getAttribute('yongjin')) || 0) / 100;
        const adRate = (Number(selectedOption.getAttribute('ad')) || 0) / 100;
        const ownerRate = (Number(selectedOption.getAttribute('dianpu')) || 0) / 100;

        const platformCommission = Number((sellingPrice * platformRate).toFixed(2));
        const adCost = Number((sellingPrice * adRate).toFixed(2));
        const ownerCommission = Number(((sellingPrice - platformCommission - adCost) * ownerRate).toFixed(2));
        const payout = Number((sellingPrice - platformCommission - adCost - ownerCommission).toFixed(2));
        const profit = Number((payout - caigou - wuliu).toFixed(2));
        const profitMargin = sellingPrice > 0 ? Number(((profit / sellingPrice) * 100).toFixed(2)) : 0;

        document.getElementById('platform-commission').value = platformCommission;
        document.getElementById('ad-cost').value = adCost;
        document.getElementById('owner-commission').value = ownerCommission;
        document.getElementById('payout').value = payout;
        document.getElementById('profit').value = profit;
        document.getElementById('profit-margin').value = profitMargin + '%';
    }

    // 人民币转日元函数
    function convertToYen(inputElem, targetId) {
        const cny = inputElem.value.trim() ? Number(inputElem.value) : 0;
        const rateElem = document.getElementById(targetId);
        const exchangeRate = Number(rateElem.getAttribute('riyuan')) || 0;
        const yen = Number((cny * exchangeRate).toFixed(2));
        rateElem.textContent = yen;
        calculateProfit();
    }

    // 全局函数：同步更新表格规格值
    function syncTableSpecValue(specType, oldValue, newValue) {
        const tableBody = document.querySelector('#link + .layui-table-view .layui-table-body tbody');
        if (!tableBody) return;

        const rows = tableBody.querySelectorAll('tr[data-index]');
        rows.forEach(row => {
            let targetCell = null;
            // 根据规格类型定位对应表格列
            if (specType === 'sku1') {
                targetCell = row.querySelector('td[data-field="209"] .layui-table-cell');
            } else if (specType === 'sku2') {
                targetCell = row.querySelector('td[data-field="211"] .layui-table-cell');
            } else if (specType === 'sku3') {
                targetCell = row.querySelector('td[data-field="213"] .layui-table-cell'); // 规格3对应列
            }

            if (targetCell && targetCell.textContent.trim() === oldValue) {
                targetCell.textContent = newValue;
            }
        });
    }

    // 辅助函数：提取规格值的核心部分
    function extractCoreValue(value) {
        // 匹配“文字+数字”格式，提取前缀文字和数字的前半部分
        const match = value.match(/^([a-zA-Zぁ-んァ-ン一-龯]+)(\d+)/);
        if (match && match[1] && match[2]) {
            // 取数字的前半部分（例如“2111”→“2”）
            const numPart = match[2].length > 1 ? match[2].substring(0, 1) : match[2];
            return match[1] + numPart;
        }
        // 无数字则返回原值
        return value;
    }

    // 辅助函数：删除表格中关联的行
    function deleteRelatedTableRows(specType, value) {
        // 1. 明确规格与表格列的映射
        const fieldMap = {
            sku1: '209',   // 规格1对应表格“バリエーション項目選択肢1”的data-field
            sku2: '211',   // 规格2对应表格“バリエーション項目選択肢2”的data-field
            sku3: '213'    // 规格3对应的数据字段
        };
        const targetField = fieldMap[specType];
        if (!targetField) {
            layer.msg('未找到对应规格列', { icon: 2 });
            return;
        }

        // 2. 提取规格值的核心部分
        const coreValue = extractCoreValue(value);

        // 3. 获取表格主体
        const tableBody = document.querySelector('#link + .layui-table-view .layui-table-body tbody');
        if (!tableBody) return;

        let deletedCount = 0;
        const rows = Array.from(tableBody.querySelectorAll('tr[data-index]'));

        rows.forEach(row => {
            // 4. 定位目标列单元格
            const cell = row.querySelector(`td[data-field="${targetField}"] .layui-table-cell`);
            if (!cell) return;

            const cellValue = cell.textContent.trim();
            // 5. 核心匹配规则：单元格值包含规格值的核心部分
            if (cellValue.includes(coreValue)) {
                row.remove(); // 删除行
                deletedCount++;

                // 6. 同步删除缓存
                const index = row.getAttribute('data-index');
                if (index !== null && layui.table.cache['link'][index]) {
                    layui.table.cache['link'].splice(index, 1);
                }
            }
        });

        // 7. 清理映射关系
        if (specValueRowMap[specType] && specValueRowMap[specType][value]) {
            delete specValueRowMap[specType][value];
        }

        // 8. 空表格处理
        if (tableBody.children.length === 0) {
            tableBody.innerHTML = '<tr><td colspan="7" style="text-align:center">暂无数据</td></tr>';
        }

        // 9. 结果提示
        if (deletedCount > 0) {
            layer.msg(`已删除 ${deletedCount} 条关联数据`, { icon: 1 });
        } else {
            console.log(`删除失败：核心值"${coreValue}"在列[data-field="${targetField}"]中未找到匹配`);
            layer.msg(`未找到与“${value}”关联的数据`, { icon: 0 });
        }
    }

    // 辅助函数：根据容器ID判断规格类型
    function getSpecTypeByContainer(containerId) {
        if (containerId === 'skuValue1Container') return 'sku1';
        if (containerId === 'skuValue2Container') return 'sku2';
        if (containerId === 'skuValue3Container') return 'sku3';
        return '';
    }

    var moduleInit = ['tool', 'tagpicker', 'tinymce', 'tablePlus'];
    function gouguInit() {
        var form = layui.form, tool = layui.tool, tagpicker = layui.tagpicker, table = layui.tablePlus;

        // 页面加载完成后初始化
        window.addEventListener('load', function() {
            document.querySelector('input[name="caigou"]').dispatchEvent(new Event('input'));
            document.querySelector('input[name="wuliu"]').dispatchEvent(new Event('input'));
            calculateProfit();
        });

        let isBasePriceModified = false;
        const originalBasePrice = parseFloat(document.querySelector('input[name="base_price"]').value) || 0;

        // 计算表格行数据
        function calculateRowData(row, isBatch = false) {
            const commissionSelect = document.querySelector('select[name="commission"]');
            const selectedCommission = commissionSelect.options[commissionSelect.selectedIndex];
            const templateType = selectedCommission?.getAttribute('data-type') || '';

            const caigou = Number(document.getElementById('m_yuan').textContent) || 0;
            const wuliu = Number(document.getElementById('m_wuliu').textContent) || 0;
            const platformRate = (Number(selectedCommission?.getAttribute('yongjin')) || 0) / 100;
            const adRate = (Number(selectedCommission?.getAttribute('ad')) || 0) / 100;
            const shopOwnerRate = (Number(selectedCommission?.getAttribute('dianpu')) || 0) / 100;

            let salePrice;
            if (isBatch || isBasePriceModified) {
                const basePrice = Number(document.querySelector('input[name="base_price"]').value) || 0;
                salePrice = basePrice + wuliu + caigou;
            } else {
                salePrice = Number(row.base_price) || 0;
            }

            const platformCommission = salePrice * platformRate;
            const adCost = salePrice * adRate;
            let shopOwnerCommission = 0;
            let payment = 0;

            if (templateType !== '6') {
                shopOwnerCommission = (salePrice - platformCommission - adCost) * shopOwnerRate;
                payment = salePrice - platformCommission - adCost - shopOwnerCommission;
            } else {
                shopOwnerCommission = 0;
                payment = salePrice - platformCommission - adCost;
            }

            const profit = payment - caigou - wuliu;
            const profitRate = salePrice > 0 ? (profit / salePrice) * 100 : 0;

            return {
                base_price: salePrice.toFixed(2),
                platform_commission: platformCommission.toFixed(2),
                ad: adCost.toFixed(2),
                shop_owner_commission: shopOwnerCommission.toFixed(2),
                payment: payment.toFixed(2),
                profit: profit.toFixed(2),
                profit_rate: profitRate.toFixed(2) + '%'
            };
        }

        // 批量更新表格所有行数据
        function updateAllRows() {
            const tableData = table.cache.link;
            if (!tableData) return;

            const newData = JSON.parse(JSON.stringify(tableData));
            for (const key in newData) {
                Object.assign(newData[key], calculateRowData(newData[key], true));
            }

            layui.pageTable.reload({
                data: newData,
                cols: layui.pageTable.config.cols
            });

            toggleShopOwnerColumn();
        }

        // 单条更新表格行数据
        function updateSingleRow(obj) {
            isBasePriceModified = false;
            const newData = calculateRowData(obj.data);
            const index = obj.tr.data('index');

            layui.table.cache.link[index] = { ...layui.table.cache.link[index], ...newData };
            layui.pageTable.reload();
        }

        // 切换店主抽佣列显示/隐藏
        function toggleShopOwnerColumn() {
            const commissionSelect = document.querySelector('select[name="commission"]');
            if (!commissionSelect) return;

            const selectedCommission = commissionSelect.options[commissionSelect.selectedIndex];
            if (!selectedCommission) return;

            const templateType = selectedCommission.getAttribute('data-type') || '';
            const tableIns = layui.pageTable;

            if (!tableIns || !tableIns.config || !Array.isArray(tableIns.config.cols) || tableIns.config.cols.length === 0 || !Array.isArray(tableIns.config.cols[0]) || tableIns.config.cols[0].length === 0) {
                return;
            }

            const cols = JSON.parse(JSON.stringify(tableIns.config.cols[0]));
            const shopOwnerColIndex = cols.findIndex(col => col.field === 'shop_owner_commission');
            if (shopOwnerColIndex !== -1) {
                cols[shopOwnerColIndex].hide = templateType === '6';
                tableIns.reload({
                    cols: [cols],
                    data: tableIns.config.data
                });
            }
        }

        // 初始化表格（含联动映射关系）
        layui.pageTable = table.render({
            elem: '#link',
            title: '店铺URL列表',
            toolbar: '#toolbarDemo',
            defaultToolbar: [],
            url: '/admin/api/get_sku_data?spu_id={$detail.spu_id}&commission={$detail.commission}',
            page: false,
            cols: [
                [{
                    field: 'id',
                    title: 'ID',
                    width: 80,
                    hide: true
                }, {
                    field: 'sku_id',
                    title: 'SKU_ID号',

                }, {
                    field: '209',
                    title: 'バリエーション項目選択肢1',

                }, {
                    field: '211',
                    title: 'バリエーション項目選択肢2',

                }, {
                    field: 'base_price',
                    title: '售价',
                },  {
                    field: 'stocks',
                    title: '库存',
                }, {
                    fixed: 'right',
                    field: 'right',
                    title: '操作',
                    width: 120,
                    toolbar: '#listRemove',
                    align: 'center'
                }]
            ],
            done: function(res) {
                // 初始化规格值与表格行的映射关系
                specValueRowMap.sku1 = {};
                specValueRowMap.sku2 = {};
                specValueRowMap.sku3 = {};

                res.data.forEach(row => {
                    // 规格1值对应表格“バリエーション項目選択肢1”列（field: '209'）
                    const sku1Value = row['209'] || '';
                    if (sku1Value) {
                        if (!specValueRowMap.sku1[sku1Value]) {
                            specValueRowMap.sku1[sku1Value] = [];
                        }
                        specValueRowMap.sku1[sku1Value].push(row.id);
                    }

                    // 规格2值对应表格“バリエーション項目選択肢2”列（field: '211'）
                    const sku2Value = row['211'] || '';
                    if (sku2Value) {
                        if (!specValueRowMap.sku2[sku2Value]) {
                            specValueRowMap.sku2[sku2Value] = [];
                        }
                        specValueRowMap.sku2[sku2Value].push(row.id);
                    }
                });

                // 初始化表格数据格式
                if (res.data && res.data.length > 0) {
                    res.data.forEach(item => {
                        item.base_price = item.adjusted_price || item.base_price || '0.00';
                    });
                }
            }
        });

        // 监听表格编辑事件
        table.on('edit(link)', function(obj) {
            if (obj.field === 'base_price') {
                updateSingleRow(obj);
            } else {
                updateSingleRow(obj);
            }
        });

        // 监听行工具事件（删除）
        table.on('tool(link)', function (obj) {
            var data = obj.data;
            if (obj.event === 'del') {
                let callback = function (e) {
                    layer.msg(e.msg);
                    if (e.code == 0) {
                        obj.del();
                    }
                }
                tool.delete("/admin/goods/del", { id: data.id }, callback);
                layer.close(index);
            }
        });

        // 监听基础价格修改（不自动刷新表格）
        document.querySelector('input[name="base_price"]').addEventListener('input', function() {
            const currentBasePrice = Number(this.value) || 0;
            isBasePriceModified = currentBasePrice !== originalBasePrice;
            // 注释掉自动刷新表格的逻辑
            // updateAllRows();
        });

        // 监听佣金选择变化
        document.querySelector('select[name="commission"]').addEventListener('change', function() {
            calculateProfit();
            updateAllRows();
        });

        // 表单提交事件
        form.on('submit(webform)', function (data) {
            // 采购价、物流费空值处理
            if (!data.field.caigou || data.field.caigou.trim() === '') {
                data.field.caigou = '0.00';
            }
            if (!data.field.wuliu || data.field.wuliu.trim() === '') {
                data.field.wuliu = '0.00';
            }

            // 强制规格值用|分隔
            const specFields = ['sku_value', 'sku_value2', 'sku_value3'];
            specFields.forEach(field => {
                if (data.field[field]) {
                    const values = data.field[field].split('|').filter(val => val.trim() !== '');
                    data.field[field] = values.join('|');
                }
            });

            // 提取表格数据
            let tableData = [];
            try {
                const tableCache = layui.table.cache['link'];
                if (Array.isArray(tableCache) && tableCache.length > 0) {
                    tableData = tableCache.map(row => ({
                        id: row.id || '',
                        sku_id: row.sku_id || '',
                        base_price: row.base_price || '',
                        stocks: row.stocks || ''
                    })).filter(item => item.id);
                } else {
                    const tableBody = document.querySelector('.layui-table-body.layui-table-main tbody');
                    if (tableBody) {
                        const rows = tableBody.querySelectorAll('tr[data-index]');
                        rows.forEach(row => {
                            const id = row.querySelector('td[data-field="id"] .layui-table-cell')?.textContent.trim() || '';
                            const skuId = row.querySelector('td[data-field="sku_id"] .layui-table-cell')?.textContent.trim() || '';
                            const basePrice = row.querySelector('td[data-field="base_price"] .layui-table-cell')?.textContent.trim() || '';
                            const stocks = row.querySelector('td[data-field="stocks"] .layui-table-cell')?.textContent.trim() || '';
                            if (id) {
                                tableData.push({ id, sku_id: skuId, base_price: basePrice, stocks: stocks });
                            }
                        });
                    }
                }

                if (tableData.length === 0) {
                    layer.msg('表格无有效数据可提交', { icon: 2 });
                    return false;
                }

            } catch (e) {
                layer.msg('提取表格数据失败: ' + e.message, { icon: 2 });
                return false;
            }

            data.field.tableData = JSON.stringify(tableData);

            // 提交表单
            let callback = function (e) {
                layer.msg(e.msg);
                if (e.code == 0) {
                    const index = parent.layer.getFrameIndex(window.name);
                    parent.layer.close(index);
                }
            }
            tool.post("/admin/goods/edit", data.field, callback);
            return false;
        });

    }

    // 读取页面规格数据
    function getPageSpecData() {
        const specList = [];

        const spec1Key = document.querySelector('input[name="sku_key"]').value.trim();
        const spec1Value = document.querySelector('input[name="sku_value"]').value.trim();
        if (spec1Key && spec1Value) {
            specList.push({
                type: 'sku1',
                key: spec1Key,
                values: [spec1Value]
            });
        }

        const spec2Key = document.querySelector('input[name="sku_key2"]').value.trim();
        const spec2Value = document.querySelector('input[name="sku_value2"]').value.trim();
        if (spec2Key && spec2Value) {
            specList.push({
                type: 'sku2',
                key: spec2Key,
                values: [spec2Value]
            });
        }

        const spec3Key = document.querySelector('input[name="sku_key3"]').value.trim();
        const spec3Value = document.querySelector('input[name="sku_value3"]').value.trim();
        if (spec3Key && spec3Value) {
            specList.push({
                type: 'sku3',
                key: spec3Key,
                values: [spec3Value]
            });
        }

        return specList;
    }

    // 价格库存修改弹窗
    document.getElementById('showSpecModal').addEventListener('click', function (e) {
        e.preventDefault();
        e.stopPropagation();

        const specList = getPageSpecData();

        let specOptionHtml = '';
        specList.forEach(spec => {
            specOptionHtml += `<option value="${spec.type}" data-key="${spec.key}">${spec.key}</option>`;
        });

        layer.open({
            type: 1,
            title: '价格库存修改',
            content: `
            <div class="pl-box" style="padding: 20px;">
                <div class="input-group">
                    <label for="specItem">规格项：</label>
                    <select id="specItem" class="layui-input" required>
                        ${specOptionHtml}
                    </select>
                </div>

                <div class="input-group mt-1" id="specValueContainer" style="display: none;">
                    <label>规格值：</label>
                    <div class="spec-value-checkboxes">
                    </div>
                </div>

                <div class="input-group mt-1" id="fullUpdateTip" style="display: none;">
                    <p class="text-danger">提示：当前规格无值，将全量更新表格中所有行</p>
                </div>

                <div class="input-group mt-1">
                    <label for="settingType">设置方式：</label>
                    <select id="settingType" class="layui-input" required>
                        <option value="base_price">售价</option>
                        <option value="stocks">库存</option>
                    </select>
                </div>

                <div class="input-group mt-1">
                    <label for="settingValue">设置值：</label>
                    <input type="text" id="settingValue" class="layui-input" placeholder="请输入数值" required>
                    <p class="text-danger mt-1" id="valueTip">提示：售价支持小数，库存需为正整数</p>
                </div>

                <button type="button" class="layui-btn layui-btn-normal mt-2" id="confirmBatchUpdate">保存</button>
            </div>
        `,
            area: ['600px', '400px'],
            success: function (layero, index) {
                layui.form.render();

                const specItemSelect = layero.find('#specItem')[0];
                const specValueContainer = layero.find('#specValueContainer')[0];
                const fullUpdateTip = layero.find('#fullUpdateTip')[0];

                specItemSelect.addEventListener('change', function() {
                    const selectedSpecType = this.value;
                    const selectedSpec = specList.find(s => s.type === selectedSpecType) || {};
                    const specValues = Array.isArray(selectedSpec.values) ? selectedSpec.values : [];
                    const hasValue = specValues.length > 0 && specValues[0];

                    if (hasValue) {
                        const splitValues = specValues[0].split('|').filter(v => v.trim() !== '');
                        if (splitValues.length > 0) {
                            specValueContainer.style.display = 'block';
                            fullUpdateTip.style.display = 'none';
                            let checkboxesHtml = '';
                            splitValues.forEach((v, index) => {
                                checkboxesHtml += `
                    <label style="display: block; margin-bottom: 5px;">
                        <input type="checkbox" name="specValue" value="${v}">
                        ${v}
                    </label>
                `;
                            });
                            specValueContainer.querySelector('.spec-value-checkboxes').innerHTML = checkboxesHtml;
                            layui.form.render('checkbox');
                        } else {
                            specValueContainer.style.display = 'none';
                            fullUpdateTip.style.display = 'block';
                        }
                    } else {
                        specValueContainer.style.display = 'none';
                        fullUpdateTip.style.display = 'block';
                    }
                });

                specItemSelect.dispatchEvent(new Event('change'));

                const settingValueInput = layero.find('#settingValue')[0];
                const settingTypeSelect = layero.find('#settingType')[0];
                const valueTip = layero.find('#valueTip')[0];

                settingValueInput.addEventListener('input', function () {
                    const value = this.value.trim();
                    const settingType = settingTypeSelect.value;

                    if (settingType === 'stocks') {
                        if (!/^[1-9]\d*$/.test(value) && value !== '') {
                            valueTip.textContent = '错误：库存需为正整数（如10、20）';
                            valueTip.style.color = '#FF5722';
                        } else {
                            valueTip.textContent = '提示：库存设置为正整数，支持批量更新表格库存列';
                            valueTip.style.color = '#666';
                        }
                    } else if (settingType === 'base_price') {
                        if (!/^\d+(\.\d{1,2})?$/.test(value) && value !== '') {
                            valueTip.textContent = '错误：售价需为非负数字（最多2位小数，如99、100.5）';
                            valueTip.style.color = '#FF5722';
                        } else {
                            valueTip.textContent = '提示：售价支持非负小数（最多2位），支持批量更新表格售价列';
                            valueTip.style.color = '#666';
                        }
                    }
                });

                settingTypeSelect.addEventListener('change', function () {
                    settingValueInput.dispatchEvent(new Event('input'));
                });
            }
        });
    });

    // 确认批量修改
    document.addEventListener('click', function (e) {
        if (e.target.id === 'confirmBatchUpdate') {
            const specItemSelect = document.getElementById('specItem');
            const settingType = document.getElementById('settingType').value;
            const settingValue = document.getElementById('settingValue').value.trim();

            if (!settingValue) {
                layer.msg('请输入设置值', { icon: 2 });
                return;
            }
            const isPriceValid = /^\d+(\.\d{1,2})?$/.test(settingValue);
            const isStockValid = /^[1-9]\d*$/.test(settingValue);
            if (settingType === 'base_price' && !isPriceValid) {
                layer.msg('售价需为非负数字（最多2位小数）', { icon: 2 });
                return;
            }
            if (settingType === 'stocks' && !isStockValid) {
                layer.msg('库存需为正整数', { icon: 2 });
                return;
            }

            const selectedSpecValues = document.querySelectorAll('input[name="specValue"]:checked');
            const specValues = Array.from(selectedSpecValues).map(checkbox => checkbox.value);
            const hasSpecValue = specValues.length > 0;

            const selectedSpecOption = specItemSelect.options[specItemSelect.selectedIndex] || {
                getAttribute: () => '未知规格'
            };
            const specKey = selectedSpecOption.getAttribute('data-key') || '未知规格';
            const specType = selectedSpecOption.value || '';

            let tableCache = [];
            const tableBody = document.querySelector('.layui-table-body.layui-table-main tbody');
            if (tableBody) {
                const rows = Array.from(tableBody.querySelectorAll('tr[data-index]'));
                rows.forEach(row => {
                    const index = row.getAttribute('data-index');
                    const id = row.querySelector('td[data-field="id"] .layui-table-cell')?.textContent || '';
                    const skuId = row.querySelector('td[data-field="sku_id"] .layui-table-cell')?.textContent || '';
                    const basePrice = row.querySelector('td[data-field="base_price"] .layui-table-cell')?.textContent || '';
                    const stocks = row.querySelector('td[data-field="stocks"] .layui-table-cell')?.textContent || '';
                    const field209 = row.querySelector('td[data-field="209"] .layui-table-cell')?.textContent || '';
                    const field211 = row.querySelector('td[data-field="211"] .layui-table-cell')?.textContent || '';
                    tableCache.push({
                        index,
                        id,
                        sku_id: skuId,
                        base_price: basePrice,
                        stocks: stocks,
                        '209': field209,
                        '211': field211
                    });
                });
            }

            if (tableCache.length === 0) {
                layer.msg('表格中无数据可更新', { icon: 2 });
                return;
            }

            let updatedCount = 0;
            tableCache.forEach((row, index) => {
                let isMatch = true;

                if (hasSpecValue) {
                    switch (specType) {
                        case 'sku1':
                            isMatch = specValues.includes(row['209']);
                            break;
                        case 'sku2':
                            isMatch = specValues.includes(row['211']);
                            break;
                        case 'sku3':
                            isMatch = specValues.includes(row['sku_value3'] || '');
                            break;
                        default:
                            isMatch = false;
                    }
                }

                if (isMatch) {
                    row[settingType] = settingValue;
                    if (layui.table && layui.table.cache['link'] && layui.table.cache['link'][index]) {
                        layui.table.cache['link'][index][settingType] = settingValue;
                    }
                    if (layui.pageTable && layui.pageTable.config && layui.pageTable.config.data && layui.pageTable.config.data[index]) {
                        layui.pageTable.config.data[index][settingType] = settingValue;
                    }

                    const tableBody = document.querySelector('.layui-table-body.layui-table-main tbody');
                    if (tableBody) {
                        const rows = tableBody.querySelectorAll('tr[data-index]');
                        if (rows[index]) {
                            const fieldIndex = settingType === 'base_price' ? 4 : 5;
                            const cell = rows[index].querySelector(`td:nth-child(${fieldIndex + 1}) .layui-table-cell`);
                            if (cell) {
                                cell.innerHTML = `<span>${settingValue}</span>`;
                            }
                        }
                    }

                    updatedCount++;
                }
            });

            let msg = '';
            if (hasSpecValue) {
                msg = updatedCount > 0
                    ? `成功匹配“${specKey}-${specValues.join('/')}”，更新${updatedCount}条数据`
                    : `未找到匹配“${specKey}-${specValues.join('/')}”的表格数据`;
            } else {
                msg = `成功全量更新，共更新${updatedCount}条数据`;
            }
            layer.msg(msg, { icon: updatedCount > 0 ? 1 : 0 });
            layer.closeAll();
        }
    });

    // 初始化标签输入功能（支持编辑、删除及联动删除表格数据）
    window.addEventListener('load', function() {
        initTagInput('skuValue1', 'skuValue1Container', '|'); // 规格1
        initTagInput('skuValue2', 'skuValue2Container', '|'); // 规格2
        initTagInput('skuValue3', 'skuValue3Container', '|'); // 规格3
    });

    /**
     * 初始化标签输入功能
     * @param {string} inputId - 隐藏输入框的ID
     * @param {string} containerId - 标签容器的ID
     * @param {string} separator - 分隔符（如|）
     */
    function initTagInput(inputId, containerId, separator) {
        const inputElem = document.getElementById(inputId);
        const containerElem = document.getElementById(containerId);

        // 从原始输入框值初始化标签
        function renderTags() {
            containerElem.innerHTML = '';
            const values = inputElem.value.split(separator).filter(val => val.trim() !== '');
            values.forEach(val => addTagToContainer(val));
        }

        // 向容器添加一个标签（支持编辑、删除、联动）
        function addTagToContainer(value) {
            const specType = getSpecTypeByContainer(containerId);
            const tag = document.createElement('div');
            tag.className = 'tag-item';
            tag.innerHTML = `
                <span class="tag-text">${value}</span>
                <span class="tag-close">×</span>
            `;
            const tagText = tag.querySelector('.tag-text');
            const tagClose = tag.querySelector('.tag-close');

            // 绑定编辑事件（单独提取为函数，方便重复调用）
            function bindEditEventToText(textElem) {
                textElem.addEventListener('click', function() {
                    const input = document.createElement('input');
                    input.type = 'text';
                    input.className = 'tag-input';
                    input.value = value;
                    input.addEventListener('blur', handleBlur);
                    input.addEventListener('keydown', handleKeydown);

                    tag.classList.add('editing');
                    tag.replaceChild(input, textElem);
                    input.focus();

                    // 失去焦点处理
                    function handleBlur() {
                        const newValue = input.value.trim();
                        if (newValue && newValue !== value) {
                            // 创建新的文本节点
                            const newText = document.createElement('span');
                            newText.className = 'tag-text';
                            newText.textContent = newValue;
                            tag.replaceChild(newText, input);
                            // 重新绑定编辑事件
                            bindEditEventToText(newText);
                            // 同步更新表格和输入框
                            syncTableSpecValue(specType, value, newValue);
                            syncTagsToInput();
                            // 更新当前值为新值（下次编辑时用）
                            value = newValue;
                        } else if (!newValue) {
                            // 空值则删除标签
                            tag.remove();
                            syncTagsToInput();
                        } else {
                            // 未修改则恢复原文本
                            tag.replaceChild(textElem, input);
                            bindEditEventToText(textElem);
                        }
                        tag.classList.remove('editing');
                    }

                    // 按键处理
                    function handleKeydown(e) {
                        if (e.key === 'Enter') input.blur();
                        if (e.key === 'Escape') {
                            tag.replaceChild(textElem, input);
                            bindEditEventToText(textElem);
                            tag.classList.remove('editing');
                        }
                    }
                });
            }

            // 首次绑定编辑事件
            bindEditEventToText(tagText);

            // 删除标签事件
            tagClose.addEventListener('click', function(e) {
                e.stopPropagation();
                const deletedValue = tagText.textContent.trim();
                tag.remove();
                syncTagsToInput();
                deleteRelatedTableRows(specType, deletedValue);
            });

            containerElem.appendChild(tag);
        }

        // 同步标签到隐藏输入框
        function syncTagsToInput() {
            const tags = containerElem.querySelectorAll('.tag-text');
            const values = Array.from(tags).map(tag => tag.textContent.trim());
            inputElem.value = values.join(separator);
        }

        // 点击容器添加新标签
        containerElem.addEventListener('click', function(e) {
            // 避免点击已有标签时触发
            if (e.target === containerElem || e.target.classList.contains('tag-container')) {
                const tempInput = document.createElement('input');
                tempInput.type = 'text';
                tempInput.placeholder = '输入后按回车添加';
                tempInput.className = 'layui-input';
                tempInput.style.width = '120px';
                tempInput.style.height = '30px';
                tempInput.style.padding = '0 8px';

                containerElem.appendChild(tempInput);
                tempInput.focus();

                tempInput.addEventListener('keydown', function(e) {
                    if (e.key === 'Enter' && tempInput.value.trim() !== '') {
                        addTagToContainer(tempInput.value.trim());
                        syncTagsToInput();
                        tempInput.remove();
                    }
                    if (e.key === 'Escape') tempInput.remove();
                });

                document.addEventListener('click', function closeTempInput(e) {
                    if (!tempInput.contains(e.target) && e.target !== containerElem) {
                        tempInput.remove();
                        document.removeEventListener('click', closeTempInput);
                    }
                });
            }
        });

        // 初始化渲染
        renderTags();
    }

</script>
{/block}
<!-- /脚本 -->